package com.example.plat.controller;

import com.example.plat.enity.User;
import com.example.plat.enity.dto.UserDto;
import com.example.plat.enity.dto.UserInfoDto;
import com.example.plat.exception.UserException;
import com.example.plat.security.DbUserDetailService;
import com.example.plat.security.JwtTokenUtil;
import com.example.plat.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;

@Api(description = "登录注册管理")
@RestController
@RequestMapping
public class LoginController {

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserService service;

    @Autowired
    ModelMapper mapper;

    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseEntity<UserInfoDto> login(@RequestBody UserDto user){
        authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword()));

        final String token = jwtTokenUtil.generateToken(user.getUserName());
        User dbUser = DbUserDetailService.getU();
        UserInfoDto dto = mapper.map(dbUser, UserInfoDto.class);
        dto.setToken(token);
        return ResponseEntity.ok(dto);
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public ResponseEntity<User> register(@RequestBody User user) throws UserException {
        User newUser = service.addUser(user);
        return ResponseEntity.ok(newUser);
    }
}
